<?php
namespace App\Admin\Controllers;
use App\Admin\Models\AdminRoles;
use App\Admin\Models\Adminusers;
use Common\ControllerAdBase;
use Phalcon\Paginator\Adapter\Model as PaginatorModel;
class AdminController extends ControllerAdBase
{

    public function initialize()
    {
        parent::initialize();
    }


    public function infoAction(){
        $adminRoles = new AdminRoles();
        $rule = $adminRoles->find_by_firstId($this->user_admin['role_group']);
        //$rule = ['/admin','/admin/info','/admin/statistics','/admin/list','/rule','/rule/list','/group/add'];
        $data = [
            'roles' =>$rule,
            'avatar' => 'https://pic.cnblogs.com/face/1083235/20180309104823.png',
            'introduction' => '这是个人介绍',
            'name' => $this->user_admin['name']
        ];
        $this->ok($data);
    }




    /**
     * 获取所有权限组
     */
    public function ruleListAction(){
        $adminroles = new AdminRoles();
        $list = $adminroles->getlist();
        $this->ok($list);
    }


    public function getadminAction(){
        if(!isset($this->params['id']) || empty($this->params['id'])){
            $this->fail(-1,'管理员id不能为空');
        }
        $adminuser = new Adminusers();
        $userinfo = $adminuser->find_by_firstId($this->params['id']);
        if($userinfo){
            //$userinfo['role_name']=$this->get_role($userinfo['role_group']);
            $this->ok($userinfo);
        }else{
            $this->fail(-1,'没有找到管理员');
        }
    }

    private function get_role($ids){
        if($ids){
            $adminrole = new AdminRoles();
            $ids_obj = $adminrole->find_by_ids($ids);
            $new_ids=[];
            foreach($ids_obj as $key=>$value){
                $new_ids[$key]=$value['name'];
            }
            return implode(',',$new_ids);
        }else{
            $this->fail(-1,'权限组错误');
        }
    }


    public function statisticsAction(){
        $this->ok([]);
    }

    public function updateadminAction(){
        if(!isset($this->params['id']) || empty($this->params['id'])){
            $this->fail(-1,'管理员id不能为空');
        }
        if($this->user_admin['id'] != 1 && $this->params['id'] != $this->user_admin['id']){
            $this->fail(-1,'您不能修改别人的记录');
        }

        $this->validate_field($this->params);
        $adminuser = new Adminusers();
        $is_user = $adminuser->find_by_firstId($this->params['id']);
        if(empty($is_user)){
            $this->fail(-1,'管理员不存在或已被删除');
        }
        $is_user['name']=$this->params['name'];
        $is_user['password']=md5($this->params['md5_password']);
        $is_user['role_group'] = implode(',',$this->params['role_group']);
        $is_user['introduction'] = $this->params['introduction'];
        $is_user['status'] = $this->params['status'];
        $result = $adminuser->save_user($is_user);
        if($result){
            $this->ok([]);
        }else{
            $this->fail(-1,'管理员修改失败');
        }
    }

    /**
     * 添加管理员
     */
    public function addadminAction(){
        $this->validate_field($this->params);
        $is_user['name']=$this->params['name'];
        $is_user['password']=md5($this->params['md5_password']);
        $is_user['role_group'] = implode(',',$this->params['role_group']);
        $is_user['introduction'] = $this->params['introduction'];
        $toolsAuthenticator = new ToolsAuthenticator();
        $is_user['google_vercode']=$toolsAuthenticator->createSecret();
        $is_user['status'] = $this->params['status'];
        $is_user['created_at'] = date('Y-m-d H:i:s',time());
        $adminuser = new Adminusers();
        $result = $adminuser->save_user($is_user);
        if($result){
            $admin_user_token = new AdminUserToken();
            $admin_arr['admin_id'] = $adminuser->id;
            $admin_arr['token'] = md5($this->params['md5_password']);
            $admin_arr['expiretime'] = date('Y-m-d H:i:s',((3600 * ToolsController::EXPIRE_HOUR) + time()));
            $admin_arr['flushtime'] = time();
            $admin_user_token->save_user($admin_arr);
            $this->ok([]);
        }else{
            $this->fail(-1,'管理员添加失败');
        }
    }


    /**
     * @param 字段验证
     */
    private function validate_field($params){
        if(empty($params['name'])){
            $this->fail(-1,'用户名不能为空');
        }else{
            $adminuser = new Adminusers();
            $is_name = $adminuser->find_by_name_validate($params['name'],$params['id']);
            if($is_name){
                $this->fail(-1,'用户名已经存在，请更换');
            }
        }

        if(isset($this->params['id']) && !empty($this->params['id'])) {
            if (empty($params['password'])) {
                $this->fail(-1, '密码不能为空');
            } else {
                if (!preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$/', $this->params['password'])) {
                    $this->fail(-1, '密码至少包含 数字和英文，长度6-18');
                }
            }
        }

        if(empty($params['status'])){
            $this->fail(-1,'是否启用该账号');
        }
        if(empty($params['role_group'])){
            $this->fail(-1,'至少选择一个权限组');
        }
    }

    public function delAction(){
        if(!isset($this->params['id']) || empty($this->params['id'])){
            $this->fail(-1,'管理员id不能为空');
        }
        if($this->params['id'] == 1){
            $this->fail(-1,'对不起，您不能删除超级管理员');
        }

        if($this->user_admin['id'] != 1 && $this->params['id'] != $this->user_admin['id']){
            $this->fail(-1,'您不能删除别人的记录');
        }

        $adminuser = new Adminusers();
        $result = $adminuser->findFirstById($this->params['id'])->delete();
        if($result){
            $this->ok([]);
        }else{
            $this->fail(-1,'管理员删除失败');
        }
    }



}
